package com.hadream.m.controller;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.jsp.PageContext;

import net.htmlparser.jericho.Source;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 */
@Controller
public class LoginC {
	
	private static final Logger logger = LoggerFactory.getLogger(LoginC.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login_get(Locale locale, Model model) {
		logger.info("Login Controller GET", locale);
		
		return "login";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login_post(Locale locale, Model model, String user_id, String password) {
		logger.info("Login Controller POST", locale);
		
		//연결
		URL url;
		try {
			//데이터
			String param = URLEncoder.encode("user_id", "UTF-8") + "=" + URLEncoder.encode("12222", "UTF-8");
			param += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
			param += "&" + URLEncoder.encode("s_url", "UTF-8") + "=" + URLEncoder.encode("http://localhost:8080/index", "UTF-8");	
			param += "&" + URLEncoder.encode("group_no", "UTF-8") + "=" + URLEncoder.encode("1", "UTF-8");	
			
			url = new URL("http://www.hadream.com/zb40pl3/login_check.php");
			
			URL u = url;
			URLConnection uc = u.openConnection();
			uc.setDoOutput(true); //Post전송
			OutputStream raw = uc.getOutputStream();
			OutputStream buffered = new BufferedOutputStream(raw);
			OutputStreamWriter out = new OutputStreamWriter(buffered,"EUC_KR");
			out.write(param);
			out.flush();
			out.close(); 
			
			//전송
//			OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
//			osw.write(param);
//			osw.flush();
		
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "redirect:index";
	}
	
	
}
